package com.jingdianchi.gateway.filter;

import cn.dev33.satoken.reactor.context.SaReactorSyncHolder;
import cn.dev33.satoken.stp.StpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 拦截登录信息
 */
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String path = request.getURI().getPath();
        log.info("path:[{}]",path);
        //放行
        if(path.equals("/user/doLogin")){
            return chain.filter(exchange);
        }
/*        //获取用户信息
        SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
        String loginId = (String) tokenInfo.getLoginId();
        log.info("loginId:[{}]",loginId);
        //存放loginId；
        mutate.header("loginId",loginId);*/
        try {
            SaReactorSyncHolder.setContext(exchange);
            String loginId = (String) StpUtil.getLoginId();
            mutate.header("loginId",loginId);
        } finally {
            SaReactorSyncHolder.clearContext();
        }
        //重新组装发送
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
